<template>
  <div>
    <!-- 面包屑导航区域 -->
   <el-breadcrumb separator-class="el-icon-arrow-right">
    <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>用户管理</el-breadcrumb-item>
    <el-breadcrumb-item>用户列表</el-breadcrumb-item>
  </el-breadcrumb>
  <!-- 头部搜索区域 -->
  <el-card class="box-card">
    <el-row :gutter="20">
      <el-col :span="7">
        <div class="grid-content bg-purple">
          <el-input placeholder="请输入内容" class="input-with-select"
          clearable v-model="queryinfo.query"
          @clear="getuserList"
          >
            <el-button slot="append" icon="el-icon-search" @click="getuserList"></el-button>
          </el-input>
        </div>
        </el-col>
        <!-- 添加用户 -->
      <el-col :span="4">
        <div class="grid-content bg-purple">
          <el-button type="primary" @click="adddialog = true">添加</el-button>
        </div>
        </el-col>
    </el-row>
    <!-- 表格数据列表 -->
    <template>
      <el-table
        :data="tableData"
        border
        stripe
        >
        <el-table-column type="index"></el-table-column>
        <el-table-column
          prop="username"
          label="用户名"
          width="140">
        </el-table-column>
        <el-table-column
          prop="mobile"
          label="电话"
          width="180">
        </el-table-column>
        <el-table-column
          prop="email"
          label="邮箱">
        </el-table-column>
        <el-table-column
          prop="role_name"
          label="角色">
        </el-table-column>
        <el-table-column
          label="状态">
          <!-- 状态切换 -->
          <template v-slot:default="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#66b1ff"
              inactive-color="#ccc"
              @change="userstatechange(scope.row)"
              >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
          label="操作">
          <!-- 编辑 删除 角色分配按钮 -->
          <template v-slot:default="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="getuserInfoById(scope.row.id)"></el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deluser(scope.row.id)"></el-button>
            <!-- 角色分配按钮 -->
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRoles(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryinfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryinfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>

      <!-- 添加用户对话框 -->
      <el-dialog
        title="添加用户"
        :visible.sync="adddialog"
        @close="closeaddDialog"
        width="30%">
        <!-- 添加用户内容区域 -->
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobbile">
            <el-input v-model="addForm.mobbile"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="adddialog = false">取 消</el-button>
          <el-button type="primary" @click="addusers">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 编辑用户对话框 -->
      <el-dialog
        title="提示"
        :visible.sync="editFormVisiable"
        @close="closeeditDialog"
        width="30%">
        <!-- 对话框内容区域 -->
        <el-form ref="editFormRef" :model="editForm" :rules="editFormRules" label-width="70px">
          <el-form-item label="用户名">
            <el-input v-model="editForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <!-- 对话框底部区域 -->
          <el-button @click="editFormVisiable = false">取 消</el-button>
          <el-button type="primary" @click="edituserinfo">确 定</el-button>
        </span>
      </el-dialog>
    </template>
  </el-card>

  <!-- 分配角色 对话框 -->
  <el-dialog
    title="分配角色"
    :visible.sync="setRolesVisiable"
    @close="closeRoleDialog"
    width="50%">
    <div>
      <p class="selectedp">当前用户：{{rolesInfo.username}}</p>
      <p class="selectedp">当前角色：{{rolesInfo.role_name}}</p>
      <p class="selectedp">设置新角色：<el-select v-model="selectedRolesId" placeholder="请选择">
      <el-option
        v-for="item in rolesList"
        :key="item.id"
        :label="item.roleName"
        :value="item.id">
      </el-option>
    </el-select>
    </p>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="setRolesVisiable = false">取 消</el-button>
      <el-button type="primary" @click="subselectedRoles">确 定</el-button>
    </span>
  </el-dialog>
  </div>
</template>


<script>
import { getdata } from '../../network/getdata'

export default {
  name:'users',
  data() {
    //邮箱自定义校验
      const checkemail = (rule,value,callback) => {
        //验证邮箱的正则表达式
        const regemail = /^[a-zA-Z0-9_-]+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])/

        if(regemail.test(value)) {
          //合法的邮箱
          callback()
        }
        //不合法的邮箱
        callback(new Error('请输入合法的邮箱'))
      }
      //电话自定义校验
      const checkmobbile = (rule,value,callback) => {
        //验证邮箱的正则表达式
        const regemobbile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/

        if(regemobbile.test(value)) {
          //合法的电话
          callback()
        }
        //不合法的邮箱
        callback(new Error('请输入合法的电话号码'))
      }
    return {
      tableData:[],
      queryinfo:{
        query:'',
        // 页码
        pagenum:1,
        //当前页显示的条数
        pagesize:2
      },
      total:0,
      //添加用户对话框是否显示 -- false 不显示
      adddialog:false,
      //添加用户信息
      addForm:{
        username:'',
        password:'',
        email:'',
        mobbile:''
      },
      //添加用户校验规则
      addFormRules:{
        username:[
          {required:true,message:'请输入用户名',trigger:'blur'},
          {min:3,max:6,message:'长度在3 到 6 个字符之间',trigger:'blur'}
        ],
        password:[
          {required:true,message:'请输入密码',trigger:'blur'},
          {min:6,max:10,message:'长度在 6 到 10 个字符之间',trigger:'blur'}
        ],
        email:[
          {required:true,message:'请输入邮箱',trigger:'blur'},
          { validator: checkemail, trigger: 'blur' }
        ],
        mobbile:[
          {required:true,message:'请输入电话',trigger:'blur'},
          { validator: checkmobbile, trigger: 'blur' }
        ]
      },
      //编辑用户信息
      editForm:{},
      // 编辑对话框的显示与隐藏 -- false 隐藏
      editFormVisiable:false,
      editFormRules:{
        email:[
          {required:true,message:'请输入邮箱',trigger:'blur'},
          {validator:checkemail,trigger:'blur'}
        ],
        mobile:[
          {required:true,message:'请输入电话号码',triiger:'blur'},
          {validator:checkmobbile,trigger:'blur'}
        ]
      },
      //分配角色对话框的显示与隐藏 false 隐藏
      setRolesVisiable:false,
      //保存分配角色的用户名和角色
      rolesInfo:{},
      // 角色列表
      rolesList:[],
      //选择的角色
      selectedRolesId:''
    }
    
  },
  methods: {
    //关闭角色分配对话框
    closeRoleDialog() {
      this.selectedRolesId = ''
      this.rolesInfo = {}
    },
    //提交角色分配
    subselectedRoles() {
      //如果没有选择，提示用户进行选择
      if(!this.selectedRolesId) {
        this.$message.info('请选择角色')
        return ;
      }
      //选择了角色,提交数据
      getdata({
        method:'put',
        url:`users/${this.rolesInfo.id}/role`,
        data:{
          rid:this.selectedRolesId
        }
      }).then((result) => {
        const res = result.data
        if(res.meta.status !== 200) {
          // 角色设置失败
          this.$message.error('分配角色失败')
          return ;
        }
        //角色分配成功
        this.$message.success('角色分配成功')
        //刷新数据
        this.getuserList();
        //关闭窗口
        this.setRolesVisiable = false
      })
    },
    //打开分配角色对话框
    setRoles(row) {
      console.log(row)
      this.rolesInfo = row
      console.log('rolesInfo',this.rolesInfo)
      //获取角色列表
      getdata({
        method:'get',
        url:'/roles'
      }).then((result) => {
        const res = result.data
        if(res.meta.status !== 200) {
          this.$message.error('获取角色列表失败')
          return ;
        }
        //获取成功
        this.rolesList = res.data
        
        // 打开对话框
        this.setRolesVisiable = true
      })
      
    },
    //删除用户
    deluser(id) {
      // console.log(id)
      //删除确认
      this.$confirm('此操作会永久删除该用户,是否继续','温馨提醒',{
        confirmButtonText:'确定',
        cancelButtonText:'取消',
        type:'warning'}).then(() => {
          //确定
          getdata({
            method:'delete',
            url:`/users/${id}`
          }).then(result => {
            const res = result.data
            if(res.meta.status !== 200) {
              this.$message.error('删除用户失败')
              return ;
            }
            //删除成功 刷新
            this.$message.success('删除用户成功')
            this.getuserList()
            
          })
        }).catch(() => {
          //取消
          this.$message.info('操作已取消')
        })
    },
    //提交修改用户的数据
    edituserinfo() {
      //先进行表单的预验证
      this.$refs.editFormRef.validate((valid) => {
        if(!valid) {
          //数据不合法
          return ;
        }
        //数据合法,提交请求
        getdata({
          method:'put',
          url:`/users/${this.editForm.id}`,
          data:{
            email:this.editForm.email,
            mobile:this.editForm.mobile
          }
        }).then((result) => {
          const res = result.data
          if(res.meta.status !== 200) {
            this.$message.error('修改失败')
            return ;
          }
          //修改成功
          //关闭窗口 更新数据
          this.$message.success(res.meta.msg)
          this.queryinfo.pagenum = 1
          this.getuserList()
          this.editFormVisiable = false
        })
      })
    },
    //关闭编辑用户信息对话框
    closeeditDialog() {
      this.$refs.editFormRef.resetFields()
    },
    //根据id 获取用户信息
    getuserInfoById(id){
      //发起请求
      getdata({
        method:'get',
        url:`/users/${id}`
      }).then((result) => {
        const res = result.data
        if(res.meta.status !== 200) {
          // 获取数据失败
          return ;
        }
        //获取数据成功
        this.editForm = res.data
        // console.log(this.editForm)
        this.editFormVisiable = true
      })
    },
    //添加用户
    addusers() {
      //先对表单进行预校验
      this.$refs.addFormRef.validate((valid) => {
        if(!valid) {
          //表单检验不通过
          return ;
        }
        //表单校验通过，发起请求
        const params = {
          username:this.addForm.username,
          password:this.addForm.password,
          email:this.addForm.email,
          mobile:this.addForm.mobbile
        }

        getdata({
          method:'post',
          url:'/users',
          data:params
        }).then(result => {
          const res = result.data
          if(res.meta.status !== 201) {
            //添加失败
            this.$message.error('添加用户失败');
            return ;
          }
          //添加用户成功
          //关闭窗口
          this.adddialog = false
          //重新刷新
          this.$message.success('添加用户成功')
          this.getuserList()
        })
      })
    },
    //关闭对话框 并重置数据清除校验
    closeaddDialog() {
      this.$refs.addFormRef.resetFields()
    },
    //用户状态切换
    userstatechange(row) {
      // console.log(row)
      getdata({
        method:'put',
        url:`users/${row.id}/state/${row.mg_state}`
      }).then(result => {
        const res = result.data;
        if(res.meta.status !== 200) {
          //设置失败
          row.mg_state = !row.mg_state
          this.$message.error('状态设置失败')
          return ;
        }
        //状态设置成功
        this.$message.success('状态设置成功')
      })
    },
    //页码变化事件
    handleCurrentChange(currentpage) {
      // console.log(currentpage)
      this.queryinfo.pagenum = currentpage
      //重新发起网络请求
      this.getuserList()
    },
    //当前页显示的条数切换按钮事件
    handleSizeChange(newpagesize) {
      // console.log(newpagesize)
      this.queryinfo.pagesize = newpagesize
      this.getuserList()
    },
    //网络请求部分
    getuserList() {
      getdata({
        method:'get',
        url:'users',
        params:this.queryinfo
      }).then((result) => {
        // console.log(res.data)
        const res = result.data
        if(res.meta.status !== 200) {
          this.$message.error(res.meta.msg)
          return ;
        }
        //获取数据成功
        this.tableData = res.data.users
        console.log(this.tableData)
        this.queryinfo.pagenum = res.data.pagenum
        this.total = res.data.total
      })
    }
  },
  created() {
    this.getuserList()
  },
}
</script>

<style lang="less" scoped>
  .el-table {
    margin-top: 15px;
  }
  .el-pagination {
    margin-top: 15px;
  }
  .selectedp {
    margin-top: 15px;
  }
</style>